#pragma once
#include <fstream>
#include <regex>
#include <sstream>
#include <sys/stat.h>
#include "../Server.hpp"

#define HTTP_TIMEOUT 10

std::unordered_map<int, std::string> statu_desc = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> mimes = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

// 工具类，里面存储的是会用到的函数，不需要实例化对象，实现成静态的即可
class Tool
{
public:
    // 以指定方式分隔字符串的函数，将源字符串，按照Sep分隔，得到子串放入vector中，返回子串的数量
    static size_t StrSplit(const std::string &src_str, const std::string &sep, std::vector<std::string> &sub_strs)
    {
        size_t begin = 0;
        // abc,def,wxd,ddd
        while (begin < src_str.size())
        {
            size_t pos = src_str.find(sep, begin);
            if (pos == begin)
            {
                begin = pos + sep.size();
                continue;
            }
            sub_strs.push_back(src_str.substr(begin, pos - begin));
            if (pos == std::string::npos)
                break;
            begin = pos + sep.size();
        }
        return sub_strs.size();
    }
    // 将文件内容读取到缓冲区中
    static bool ReadFile(const std::string &file_path, std::string &buffer)
    {
        std::ifstream in(file_path, std::ios::binary);
        if (!in.is_open())
        {
            ERROR_LOG("Open %s File Error!", file_path.c_str());
            return false;
        }
        in.seekg(0, in.end);
        size_t file_lenth = in.tellg();
        in.seekg(0, in.beg);
        buffer.resize(file_lenth);
        in.read(&buffer[0], file_lenth);
        if (!in.good())
        {
            in.close();
            return false;
        }
        in.close();
        return true;
    }
    // 将缓冲区中的内容写入到文件中
    static bool WriteFile(const std::string &file_path, const std::string &buffer)
    {
        std::ofstream out(file_path, std::ios::binary | std::ios::trunc);
        if (!out.is_open())
        {
            ERROR_LOG("Open %s File Error!", file_path.c_str());
            return false;
        }
        out.write(buffer.c_str(), buffer.size());
        if (!out.good())
        {
            out.close();
            return false;
        }
        out.close();
        return true;
    }

// RFC3986规定的不编码的字符：
// 字母：大写字母 A - Z 和小写字母 a - z。
// 数字：0 - 9。
// 特殊符号：-（连字号）、_（下划线）、.（句号）、~（波浪号）。
// W3C文档中规定，查询字符串中的空格需要编码为+ 解码就是+转空格
#define ENABLE_SPACE_TO_PLUS 1
    static std::string UrlEncode(const std::string &url, bool flag = false)
    {
        std::string ret;
        for (auto &c : url)
        {
            if (c == '-' || c == '_' || c == '.' || c == '~' || isalnum(c) /*判断是不是字母或数字*/)
            {
                ret += c;
                continue;
            }
            if (c == ' ' && flag)
            {
                ret += '+';
                continue;
            }
            char tmp[4] = {0};                       // 存储%HH格式
            snprintf(tmp, sizeof(tmp), "%%%02X", c); // 这里写入的是字符串，至少要多给一个'\0'的空间
            ret += tmp;
        }
        return ret;
    }

    static int HexCharToDec(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c - '0';
        }
        if (c >= 'a' && c <= 'e')
        {
            return c - 'a' + 10;
        }
        if (c >= 'A' && c <= 'E')
        {
            return c - 'A' + 10;
        }
        return -1;
    }

    static std::string UrlDecode(const std::string &url, bool flag = 0)
    {
        std::string ret;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '%' && i + 2 < url.size() /*防止访问越界*/)
            {
                // 2B -> Dex ->+
                char c = (HexCharToDec(url[i + 1]) << 4) + (HexCharToDec(url[i + 2]));
                ret += c;
                i += 2;
                continue;
            }
            if (url[i] == '+' && flag)
            {
                ret += ' ';
                continue;
            }
            ret += url[i];
        }

        return ret;
    }

    static std::string GetStatuDesc(int status_code)
    {
        auto it = statu_desc.find(status_code);
        if (it == statu_desc.end())
        {
            return "UNKNOWN CODE";
        }
        return it->second;
    }

    static std::string GetMimeType(const std::string &filename)
    {
        size_t pos = filename.rfind(".");
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string ext = filename.substr(pos);
        auto it = mimes.find(ext);
        if (it == mimes.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }

    static bool IsDirectory(const std::string &pathname)
    {
        struct stat filestat = {0};
        int ret = stat(pathname.c_str(), &filestat);
        if (ret < 0) // 文件不存在默认返回错误
            return false;
        /// usr/include/linux/stat.h:#define S_ISDIR(m)	(((m) & S_IFMT) == S_IFDIR)
        return S_ISDIR(filestat.st_mode);
    }

    static bool IsRegularFile(const std::string &pathname)
    {
        struct stat filestat = {0};
        int ret = stat(pathname.c_str(), &filestat);
        if (ret < 0)
            return false;
        // /usr/include/linux/stat.h:#define S_ISREG(m)	(((m) & S_IFMT) == S_IFREG)
        return S_ISREG(filestat.st_mode);
    }

    // 防止访问时跳出了相对根目录
    static bool IsPathValid(const std::string &pathname)
    {
        int level = 0;
        // 解析目录
        std::vector<std::string> dirs;
        StrSplit(pathname, "/", dirs);
        for (auto &dir : dirs)
        {
            if (dir == "..")
            {
                level--;
                if (level < 0)
                    return false; // 只要跳出相对根目录，就无效
                continue;
            }
            level++;
        }
        return true;
    }
};

// Http请求报文模块
class HttpRequest
{
public:
    // 存储请求报文的要素
    std::string _method;                                 // 请求方法
    std::string _path;                                   // 资源路径
    std::unordered_map<std::string, std::string> _args;  // 查询字符型
    std::string _version;                                // 协议版本
    std::unordered_map<std::string, std::string> _heads; // 请求头
    std::string _body;                                   // 请求体
    std::smatch _matches;                                // 存储未来正则解析出请求方法的内容
public:
    HttpRequest() : _version("HTTP/1.1") {}
    void Clear()
    {
        _method.clear();
        _path.clear();
        _args.clear();
        _version = "HTTP/1.1";
        _heads.clear();
        std::smatch matches;
        _matches.swap(matches);
        _body.clear();
    }
    // 未来方便使用的接口
    void SetHead(const std::string &key, const std::string &val)
    {
        _heads.insert(std::make_pair(key, val));
    }

    bool HeadExist(const std::string &key)
    {
        auto it = _heads.find(key);
        if (it == _heads.end())
            return false;
        return true;
    }

    std::string GetHead(const std::string &key)
    {
        if (!HeadExist(key))
            return "";
        return _heads[key];
    }
    void SetArg(const std::string &key, const std::string &val)
    {
        _args.insert(std::make_pair(key, val));
    }
    bool ArgExist(const std::string &key)
    {
        auto it = _args.find(key);
        if (it == _args.end())
            return false;
        return true;
    }
    std::string GetArg(const std::string &key)
    {
        if (!HeadExist(key))
            return "";
        return _args[key];
    }
    size_t GetBodyLength()
    {
        if (!HeadExist("Content-Length"))
        {
            return 0;
        }
        return std::stol(_heads["Content-Length"]);
    }
    // 判断是否是短连接
    bool IsShortLink()
    {
        // 不存在或者为close都视为短连接
        if (!HeadExist("Connection") || GetHead("Connection") == "close")
            return true;        
        if (GetHead("Connection") == "keep-alive")
            return false;
        return true;
    }

    // for debug
    std::string Serialize() const
    {
        std::stringstream req_str;
        if (_heads.empty())
        {
            DEBUG_LOG("head empty");
        }
        req_str << _method << " " << _path << " " << _version << "\r\n";
        for (auto &arg : _args)
        {
            req_str << arg.first << ": " << arg.second << "\r\n";
        }
        for (auto &head : _heads)
        {
            req_str << head.first << ": " << head.second << "\r\n";
        }
        req_str << "\r\n";
        req_str << _body;
        // DEBUG_LOG("%s",req_str.str().c_str());
        return req_str.str();
    }
};


class HttpResponse
{
public:
    HttpResponse(int status_code = 200)
        : _status_code(status_code), _is_redirect(false)
    {
    }
    void Clear()
    {
        _version.clear();
        _status_code = 200;
        _heads.clear();
        _body.clear();
        _is_redirect = false;
    }

    void SetHead(const std::string &key, const std::string &val)
    {
        _heads.insert(std::make_pair(key, val));
    }

    bool HeadExist(const std::string &key)
    {
        auto it = _heads.find(key);
        if (it == _heads.end())
            return false;
        return true;
    }

    std::string GetHead(const std::string &key)
    {
        if (!HeadExist(key))
            return "";
        return _heads[key];
    }

    void SetBody(const std::string body, const std::string &type = "text/html")
    {
        _body = body;
        SetHead("Content-Type", type);
    }
    void SetRedir(const std::string &url, int status_code = 304)
    {
        _redirect_url = url;
        _status_code = status_code;
    }

    // 判断是否是短连接
    bool IsShortLink()
    {
        // 不存在或者为close都视为短连接
        if (!HeadExist("Connection") || GetHead("Connection") == "close")
            return true;
        if (GetHead("Connection") == "keep-alive")
            return false;
        return true;
    }

    std::string Serialize()
    {
        std::stringstream res_str;
        res_str << "HTTP/1.1" << " " << _status_code << " " << Tool::GetStatuDesc(_status_code) << "\r\n";
        for (auto &head : _heads)
        {
            res_str << head.first << ": " << head.second << "\r\n";
        }
        res_str << "\r\n";
        res_str << _body;
        return res_str.str();
    }

public:
    std::string _version;                                // 协议版本
    int _status_code;                                    // 状态码
    std::unordered_map<std::string, std::string> _heads; // 响应头
    std::string _body;                                   // 响应体
    bool _is_redirect;                                   // 是否重定向
    std::string _redirect_url;                           // 重定向url
};

// 当前接收所处的阶段状态
typedef enum
{
    HTTP_RECV_ERROR,
    HTTP_RECV_LINE,
    HTTP_RECV_HEAD,
    HTTP_RECV_BODY,
    HTTP_RECV_OVER
} recv_status_t;
#define MAX_URL_SIZE 8 * 1024 // 最大限制8KB
// 接收请求报文的上下文
class HttpContent
{
private:
    bool ParseLine(const std::string &line)
    {
        // DEBUG_LOG("开始解析请求行:%s", line.c_str());
        std::smatch matches;
        // 使用正则表达式解析
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase /*忽略大小写提取*/);
        bool ret = std::regex_match(line, matches, e);
        if (ret == false)
        {
            _status_code = 400; // BAD REQUEST
            _recv_status = HTTP_RECV_ERROR;
            // DEBUG_LOG("解析请求行失败！");
            return false;
        }
        // 1 : GET  请求方法
        // 2 : /baidu/login  资源路径   需要Decode
        // 3 : user=zhangsan&pass=123123  查询字符串   需要Decode
        // 4 : HTTP/1.1  协议版本
        _request._method = matches[1];
        // 转换请求方法为大写，方便后续处理
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), toupper);
        _request._path = Tool::UrlDecode(matches[2]);
        // 设置并解析查询字符串
        std::string quary_str = matches[3];
        std::vector<std::string> substrs;
        Tool::StrSplit(quary_str, "&", substrs);
        for (auto &str : substrs)
        { // user=zhangsan
            size_t pos = str.find("=");
            if (pos == std::string::npos)
            {
                _status_code = 400; // BAD REQUEST
                _recv_status = HTTP_RECV_ERROR;
                // DEBUG_LOG("解析请求行失败！");
                return false;
            }
            // 找到了，Decode一下，并设置进去，查询字符串需要空格转加号
            std::string key = Tool::UrlDecode(str.substr(0, pos), ENABLE_SPACE_TO_PLUS);
            std::string val = Tool::UrlDecode(str.substr(pos + 1), ENABLE_SPACE_TO_PLUS);
            _request.SetArg(key, val);
        }
        _request._version = matches[4];
        return true;
    }

    bool RecvLine(Buffer &inbuffer)
    {
        // DEBUG_LOG("开始接收请求行");
        // 先尝试接收请求行
        std::string line;
        line = inbuffer.GetLine();
        // 判断是否是完整的一行
        if (line.size() == 0)
        {
            // 不是完整的一行，判断是否是一个过大的请求行
            if (inbuffer.ReadSize() > MAX_URL_SIZE)
            {
                // 请求行过大，返回错误
                _status_code = 414; // URI TOO LONG
                _recv_status = HTTP_RECV_ERROR;
                return false;
            }
            // 不是完整的一行，但是也没超限，返回留待继续接收
            return true;
        }
        // 收到了完整的一行，调用解析函数
        bool ret = ParseLine(line);
        if (ret == false) // 解析函数会设置好错误信息
            return false;
        // 解析正确，进入下一阶段
        // DEBUG_LOG("解析正确，进入下一阶段");
        _recv_status = HTTP_RECV_HEAD;
        return true;
    }
    bool ParseHead(std::string head)
    {
        // DEBUG_LOG("开始解析请求头");
        // key: val\r\n
        // 先去除掉\r\n
        size_t pos = head.rfind("\n");
        if (pos != std::string::npos)
            head.pop_back();
        pos = head.rfind("\r");
        if (pos != std::string::npos)
            head.pop_back();

        pos = head.find(": ");
        if (pos == std::string::npos)
        {
            _status_code = 400; // BAD REQUEST
            _recv_status = HTTP_RECV_ERROR;
            return false;
        }
        // 找到了，Decode一下，并设置进去，查询字符串需要空格转加号

        std::string key = head.substr(0, pos);
        std::string val = head.substr(pos + 2);
        // DEBUG_LOG("key=%s:val=%s",key.c_str(),val.c_str());
        _request.SetHead(key, val); // val\r\n
        return true;
    }
    bool RecvHead(Buffer &inbuffer)
    {
        // DEBUG_LOG("开始接收请求头");
        // DEBUG_LOG("inbuffer: %s",inbuffer.ReadPtr());
        if (_recv_status != HTTP_RECV_HEAD)
        {
            DEBUG_LOG("return false;");
            return false;
        }

        while (true)
        {
            // key:val\r\n
            std::string head = inbuffer.GetLine();
            // DEBUG_LOG("head :%s\n",head.c_str());
            //  检测是否是完整的一行
            if (head.size() == 0)
            {                // 不是一个完整的一行
                return true; // 回去继续接收
            }
            // 是完整的一行，判断是否是空行
            if (head == "\r\n" || head == "\n")
            {
                // 是空行，头部解析完成，跳出循环
                _recv_status = HTTP_RECV_BODY;
                return true;
            }

            bool ret = ParseHead(head);
            if (ret == false)
                return false;
            // 失败返回，成功继续解析
        }
    }

    bool RecvBody(Buffer &inbuffer)
    {
        // DEBUG_LOG("开始接收请求体");
        if (_recv_status != HTTP_RECV_BODY)
            return false;
        size_t content_length = _request.GetBodyLength();
        if (content_length == 0)
        {
            // 如果请求体为空，直接解析完成
            _recv_status = HTTP_RECV_OVER;
            return true;
        }

        // 计算剩余应该读取的长度
        size_t remain_lenth = content_length - _request._body.size() /*当前已经接收的长度*/;
        DEBUG_LOG("remain_length:%ld", remain_lenth);
        DEBUG_LOG("inbuffer_length:%ld", inbuffer.ReadSize());
        static int i = 1;
        DEBUG_LOG("执行次数：%d\n", i++);
        // 可以读完，读取后返回
        if (remain_lenth <= inbuffer.ReadSize() /*本次一定能读完*/)
        {
            // DEBUG_LOG("可以读完，读取后返回");
            // 读进来

            _request._body.append(inbuffer.ReadPtr(), remain_lenth);
            inbuffer.UpdateReadOffset(remain_lenth);
            // 解析完成
            _recv_status = HTTP_RECV_OVER;
            // 读完之后设置进去
            return true;
        }
        // 本次不能读完，先读取能读取的，留待下次继续
        _request._body.append(inbuffer.ReadPtr(), inbuffer.ReadSize());
        // 移动读偏移
        inbuffer.UpdateReadOffset(inbuffer.ReadSize());
        return true;
    }

public:
    HttpContent()
        : _status_code(200), _recv_status(HTTP_RECV_LINE)
    {
        //_request.Clear();
    }
    void Clear()
    {
        _status_code = 200;
        _recv_status = HTTP_RECV_LINE;
        _request.Clear();
    }
    // 返回当前处理结果的状态码
    int GetStatusCode()
    {
        return _status_code;
    }
    // 返回当前接收阶段状态，外部主要关注：ERROR或OVER状态。
    recv_status_t GetRecvStatus()
    {
        return _recv_status;
    }
    // 核心接口，接收报文，逐步构建HttpRequest结构
    void RecvHttpRequest(Buffer &inbuffer)
    {
        switch (_recv_status)
        {
        // 接收完Line，立马接收Head...不需要break
        case HTTP_RECV_LINE:
            RecvLine(inbuffer);
        case HTTP_RECV_HEAD:
            RecvHead(inbuffer);
        case HTTP_RECV_BODY:
            RecvBody(inbuffer);
        }
    }
    // 返回请求报文
    HttpRequest &GetRequest()
    {
        return _request;
    }

private:
    int _status_code;           // 用于获取当前处理结果的状态码
    recv_status_t _recv_status; // 记录当前接收的阶段状态
    HttpRequest _request;       // 根据接收的请求报文，构建的请求报文结构
};

class HttpServer
{
    // 外部传入的方法类型
    using http_handler_t = std::function<void(const HttpRequest &, HttpResponse *)>;
    using http_handlers_t = std::vector<std::pair<std::regex, http_handler_t>>;

private:
    // 供各个函数检测发现失败后调用，构建应答报文并发送回去
    void ErrorHandler(ConnectionPtr &conn, const HttpRequest &req, HttpResponse *res)
    {
        // 1. 组织一个错误展示页面(后续替换成文件形式，这里简单组织一下)
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(res->_status_code);
        body += " ";
        body += Tool::GetStatuDesc(res->_status_code);
        body += "</h1>";
        body += "</body>";
        body += "</html>";

        // 2. 将页面数据，当作响应正文，放入res中
        res->SetBody(body);
        // 统一选择在发送之前组织报头
        res->SetHead("Content-Length", std::to_string(res->_body.size()));
        res->SetHead("Content-Type", Tool::GetMimeType("404.html"));
        if (res->IsShortLink())
            res->SetHead("Connection", "close");
        else
            res->SetHead("Connection", "keep-alive");

        // 构建应答报文字符串
        std::string res_str = res->Serialize();
        // DEBUG_LOG("发送的错误响应报文：%s", res_str.c_str());
        // 发送回去
        conn->SendInLoop(res_str.c_str(), res_str.size());
    }

    // 判断是否可能是静态资源
    bool IsStaticResource(const HttpRequest &req)
    {
        // 认为只有Get 和 Head才可能是静态资源的请求
        if (req._method == "GET" /*|| req._method == "HEAD"*/)
            return true;
        return false;
    }
    // 尝试发送静态资源
    bool SendStaticResouse(HttpRequest &req, HttpResponse *res)
    {
        // 先把路径尝试补充完整(申请目录默认补充首页)
        std::string path = req._path;
        path = _root_dir + path;
        if (path.back() == '/')
        {
            path += "index.html";
        }
        // 是静态资源，判断路径有效性
        if (!Tool::IsPathValid(path))
            return false;
        // 路径有效判断资源是否存在
        if (!Tool::IsRegularFile(path))
        {
            // DEBUG_LOG("资源不存在");
            return false;
        }

        // 确认是一个有效且存在的文件
        req._path = path;
        // 构建响应
        int ret = Tool::ReadFile(path, res->_body);
        if (ret == false)
            return false;
        return true;
    }

    void Dispatcher(HttpRequest &req, HttpResponse *res, http_handlers_t regex_handlers)
    {
        for (auto &regex_hanler : regex_handlers)
        {
            // 进行正则匹配
            std::regex reg = regex_hanler.first;
            const http_handler_t &handler = regex_hanler.second;
            bool ret = std::regex_match(req._path, req._matches, reg);
            if (ret == true)
            {
                handler(req, res);
                // 在handler内构建应答
                return;
            }
        }
        // 找不到，返回404
        res->_status_code = 404;
        // DEBUG_LOG("找不到这个GET方法，返回404");
    }
    void Route(HttpRequest &req, HttpResponse *res)
    {
        // 判断请求的是否可能是静态资源
        if (IsStaticResource(req))
        {
            if (SendStaticResouse(req, res)) // 是静态资源则尝试发送
                return;                      // 发送成功则返回，失败则去判断是否是请求具体的方法
        }
        // DEBUG_LOG("进行方法的路由");
        //  进行方法的路由
        if (req._method == "GET")
            return Dispatcher(req, res, _get_route); // 在内部进行正则判断
        else if (req._method == "POST")
            return Dispatcher(req, res, _post_route);
        else if (req._method == "PUT")
            return Dispatcher(req, res, _put_route);
        else if (req._method == "DELETE")
            return Dispatcher(req, res, _delete_route);
        // 没有匹配的方法，返回405"Method Not Allowed"
        // DEBUG_LOG("没有匹配的方法，返回 405 Method Not Allowed");
        res->_status_code = 405;
    }

    // 连接建立后的回调，设置上下文
    void EstablishedHandler(ConnectionPtr conn)
    {
        conn->SetContent(HttpContent()); // 设置个匿名对象给这个Any类型初始化
        // DEBUG_LOG("void EstablishedHandler(ConnectionPtr conn)");
        INFO_LOG("New Connection:%p", conn.get());
    }
    // 收到消息后的回调
    void MessageHandler(ConnectionPtr conn, Buffer *inbuffer)
    {
        // 缓冲区内可能有多条完整报文，只要缓冲区还有数据本次就一直处理（除非是短连接），直到处理到不是完整的报文就返回了，继续接收
        while (inbuffer->ReadSize() > 0)
        {
            //  DEBUG_LOG("开始解析报文");
            //  首先解析上下文
            HttpContent *content = conn->GetContent()->Get<HttpContent>();
            content->RecvHttpRequest(*inbuffer);
            HttpRequest &request = content->GetRequest();
            // DEBUG_LOG("request :%s ", request.Serialize().c_str());
            HttpResponse response;
            // 设置解析的状态码
            response._status_code = content->GetStatusCode();
            // DEBUG_LOG("content->GetRecvStatus():%d", content->GetRecvStatus());
            // 判断解析是否失败 or 不完整
            if (response._status_code >= 400)
            { // 解析失败，调用失败处理的接口
                DEBUG_LOG("解析出错");
                ErrorHandler(conn, request, &response); // 在内部设置好响应正文

                // 清空上下文，清空缓冲区
                content->Clear();
                // DEBUG_LOG("GetStatusCode():%d", conn->GetContent()->Get<HttpContent>()->GetStatusCode());
                inbuffer->UpdateReadOffset(inbuffer->ReadSize()); // 请求出错了就清空缓冲区数据不再处理了，继续处理已经无意义，后续关闭连接前检查缓冲区时就不会再进行接受了
                //  关闭连接
                conn->DisConnectInLoop();
                return;
            }
            // 判断缓冲区数据是否构成了完整的报文
            if (content->GetRecvStatus() != HTTP_RECV_OVER)
            {
                DEBUG_LOG("本次接受不完整，返回");
                // 不是完整报文，直接返回，继续等待新内容
                return;
            }
            //  DEBUG_LOG("准备进行路由");
            // 是完整报文：调用路由函数执行具体处理
            Route(request, &response); // 在内部会构建好应答
            if (response._status_code >= 400)
            {
                ErrorHandler(conn, request, &response);
                // 关闭连接
                conn->DisConnectInLoop();
                return;
            }

            // 构建响应报文->字符串
            response.SetHead("Content-Length", std::to_string(response._body.size()));
            response.SetHead("Content-Type", Tool::GetMimeType(request._path));
            if (request.IsShortLink())
                response.SetHead("Connection", "close");
            else
                response.SetHead("Connection", "keep-alive");
            // 判断是否重定向
            if (response._is_redirect == true)
                response.SetHead("Location", response._redirect_url);
            std::string res_str = response.Serialize();
            // 发送回去
            // DEBUG_LOG("本次的应答报文：%s", res_str.c_str());
            conn->SendInLoop(res_str.c_str(), res_str.size());

            // 如果是短连接直接关闭连接，否则继续处理
            if (request.IsShortLink())
                conn->DisConnectInLoop();
           
            // 清空本次的上下文
            content->Clear();
        }
    }

    void ReleaseConnHandler(ConnectionPtr conn)
    {
        INFO_LOG("Release connection:%p", conn.get());
    }

public:
    HttpServer(uint16_t port, size_t slave_cnt, uint32_t timeout = HTTP_TIMEOUT) : _tcp_server(port, slave_cnt)
    {
        _tcp_server.EnableTimeoutRelease(timeout);
        _tcp_server.SetEstablishCallback(std::bind(&HttpServer::EstablishedHandler, this, std::placeholders::_1));
        _tcp_server.SetMsgHandlerCallback(std::bind(&HttpServer::MessageHandler, this, std::placeholders::_1, std::placeholders::_2));
        _tcp_server.SetReleaseCallback(std::bind(&HttpServer::ReleaseConnHandler, this, std::placeholders::_1));
    }
    void SetGetHandler(std::regex regex_str, const http_handler_t &handler)
    {
        // std::vector<std::pair<std::regex, http_handler_t>>;
        _get_route.push_back(std::make_pair(regex_str, handler));
    }
    void SetPostHandler(std::regex regex_str, const http_handler_t &handler)
    {
        _post_route.push_back(std::make_pair(regex_str, handler));
    }
    void SetPutHandler(std::regex regex_str, const http_handler_t &handler)
    {
        _put_route.push_back(std::make_pair(regex_str, handler));
    }
    void SetDeleteHandler(std::regex regex_str, const http_handler_t &handler)
    {
        _delete_route.push_back(std::make_pair(regex_str, handler));
    }
    void Start()
    {
        _tcp_server.Start();
    }
    void SetRootDir(const std::string root_dir)
    {
        // 不存在则创建
        if (!Tool::IsDirectory(root_dir))
        {
            assert(false);
            // mkdir(root_dir.c_str(),0666);
        }
        _root_dir = root_dir;
    }

private:
    TcpServer _tcp_server;
    // 各种方法对应的路由表
    http_handlers_t _get_route;
    http_handlers_t _post_route;
    http_handlers_t _put_route;
    http_handlers_t _delete_route;
    std::string _root_dir;
};